package com.zhilianbao.leyaogo.ui.fragment.address;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.text.InputType;
import android.view.View;

import com.bql.convenientlog.CLog;
import com.bql.pickerview.OptionsPickerView;
import com.bql.roundview.RoundTextView;
import com.bql.utils.AsyncTaskUtils;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.bql.utils.ThreadPool;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AddressApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.model.entity.BaseBean;
import com.zhilianbao.leyaogo.model.response.address.Address;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseOkHttpFragment;
import com.zhilianbao.leyaogo.utils.AddressUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.widgets.ModifyView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;


/**
 * Author: hcy
 * Description:修改收货地址
 * Created: 2016/10/25 8:58
 */
public class ModifyAddressFragment extends BaseOkHttpFragment implements ModifyView.OnItemClickListener {

    private static final String KEY_CHANGE = "change";
    private static final String KEY_DATA = "data";
    private static final int TAG_SELECT_CITY = 2;

    @BindViews({R.id.mv_receive_name, R.id.mv_phone, R.id.mv_city, R.id.mv_address})
    public List<ModifyView> mModifyViews;//收货人，联系电话，省市区，详细地址

    @BindView(R.id.switch_use_default)
    public SwitchCompat mSwitchCompat;

    @BindView(R.id.tv_add_address)
    RoundTextView mRoundTextView;

    private boolean change, isDefault;//是编辑改变地址还是新增地址,是否默认地址
    private Address mAddress;

    private OptionsPickerView mCityPickerView;
    private String province, provinceStr = "";
    private String city, cityStr = "";
    private String area, areaStr = "";

    private long userId, supplierId;
    private ArrayList<BaseBean> list1;
    private ArrayList<ArrayList<BaseBean>> list2;
    private ArrayList<ArrayList<ArrayList<BaseBean>>> list3;

    private AsyncTask<Void, Void, Boolean> mAsyncTask;
    private AsyncTask<Void, Void, Void> mParseTask;

    public static ModifyAddressFragment getInstance(boolean change, Address address) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(KEY_CHANGE, change);
        if (change) {
            bundle.putParcelable(KEY_DATA, address);
        }
        ModifyAddressFragment fragment = new ModifyAddressFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_modify_address;
    }

    @Override
    protected void initToolbarHere() {
        change = getArguments().getBoolean(KEY_CHANGE, true);
        if (change) {
            mAddress = getArguments().getParcelable(KEY_DATA);
            isDefault = mAddress.getIsDefault() == 1;
            initToolbar(getString(R.string.modify_receive_address), "", getString(R.string.modify_delete), 0, 0, 0, 0);
        } else {
            initToolbar(getString(R.string.modify_receive_address_add));
        }
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {

        //设置
        mModifyViews.get(0).setIvGone();
        mModifyViews.get(0).setItemName(getString(R.string.modify_name));

        mModifyViews.get(1).setIvGone();
        mModifyViews.get(1).setItemName(getString(R.string.modify_phone));
        mModifyViews.get(1).setModifyEtInputType(InputType.TYPE_CLASS_PHONE);
        mModifyViews.get(1).setModifyEtLength(11);

        mModifyViews.get(2).setIvShow();
        mModifyViews.get(2).setItemName(getString(R.string.modify_city));
        mModifyViews.get(2).setModifyItemCanEdit(false);
        mModifyViews.get(2).setOnItemClickListener(this, TAG_SELECT_CITY);

        mModifyViews.get(3).setIvGone();
        mModifyViews.get(3).setItemName(getString(R.string.modify_detail));

        if (!change) {
            mModifyViews.get(0).setModifyItemHintText(getString(R.string.modify_hint_name));
            mModifyViews.get(1).setModifyItemHintText(getString(R.string.modify_hint_phone));
            mModifyViews.get(2).setModifyItemHintText(getString(R.string.modify_hint_city));
            mModifyViews.get(3).setModifyItemHintText(getString(R.string.modify_hint_detail));
        } else {
            mModifyViews.get(0).setModifyItemText(mAddress.getAdName());
            mModifyViews.get(1).setModifyItemText(mAddress.getAdPhone());
            mModifyViews.get(3).setModifyItemText(mAddress.getAddress());
            mSwitchCompat.setChecked(mAddress.getIsDefault() == 1);
            province = mAddress.getProvince();
            city = mAddress.getCity();
            area = mAddress.getArea();
            setSaveBtnClickable(false);//解析出省市区的名称才能点击保存
        }
        isAddressListDataOk();
        supplierId = Utils.getSupplierId();
        userId = Utils.getUserLoginInfo().getUserId();
    }

    /**
     * 省市区数据是否已经解析存储
     *
     * @return ok
     */
    private void isAddressListDataOk() {
        mAsyncTask = new GetAddressListTask();
        mAsyncTask.execute();
    }

    /**
     * 读取任务
     */
    private class GetAddressListTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Void... params) {
            list1 = Utils.getProvinceList();
            list2 = Utils.getCityList();
            list3 = Utils.getDistrictList();
            if (list1 == null || list1.size() == 0 || list2 == null || list2.size() == 0 || list3 == null || list3.size() == 0) {
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aVoid) {
            super.onPostExecute(aVoid);
            if (!aVoid) {//没有存储
                getAddress();//解析存储到sp
            } else {
                getNameById();
            }
        }
    }

    /**
     * 初始化城市选择器
     */
    private void initCityPicker(int index1, int index2, int index3) {

        mCityPickerView = new OptionsPickerView(mActivity);
        mCityPickerView.setPicker(list1, list2, list3, true);
        mCityPickerView.setCyclic(false);
        mCityPickerView.setTitle("选择城市");
        mCityPickerView.setCancelable(true);
        mCityPickerView.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                try {
                    provinceStr = list1.get(options1).getName();
                    province = list1.get(options1).getId();

                    cityStr = list2.get(options1).size() == 0 ? "" : list2.get(options1).get(option2).getName();

                    city = list2.get(options1).size() == 0 ? "" : list2.get(options1).get(option2).getId();

                    areaStr = (list3.get(options1).get(option2).size() == 0 ?
                            "" : list3.get(options1).get(option2).get(options3).getName());

                    area = (list3.get(options1).get(option2).size() == 0 ?
                            "" : list3.get(options1).get(option2).get(options3).getId());
                    CLog.i("hcy", "province=" + province + "city=" + city + "area=" + area);
                    StringBuilder builder = new StringBuilder(provinceStr);
                    builder.append(cityStr).append(areaStr);
                    mModifyViews.get(2).setModifyItemText(builder.toString());
                } catch (Exception e) {
                    CLog.e(e.toString());
                }
            }

            @Override
            public void onCancel(int options1, int option2, int options3) {
            }
        });
        mCityPickerView.setContentBackGroundColor(getResources().getColor(R.color.white));
        mCityPickerView.setLineVisible(false, false);
        mCityPickerView.setTitleTextColorSize(getResources().getColor(R.color.color_333333), 15);
        mCityPickerView.setBtnCancelTextColorSize(getResources().getColor(R.color.color_333333), 14);
        mCityPickerView.setBtnSubmitTextColorSize(getResources().getColor(R.color.color_333333), 14);
        mCityPickerView.setStyle(2f, getResources().getColor(R.color.transparent)
                , getResources().getColor(R.color.color_333333), getResources().getColor(R.color.color_999999), 9, 11);
        if (change) {
            mCityPickerView.setSelectOptions(index1, index2, index3);
        }
    }

    /**
     * 增加收货地址请求
     */
    private void addAddress() {
        int isDef = mSwitchCompat.isChecked() ? 1 : 0;
        String strAddress = mModifyViews.get(2).getModifyEditText() + mModifyViews.get(3).getModifyEditText();
        AddressApi.addAddress(mActivity, userId, supplierId, isDef, mModifyViews.get(0).getModifyEditText(), mModifyViews.get(1).getModifyEditText(),
                province, city, area, strAddress, mModifyViews.get(3).getModifyEditText(),
                new DialogCallback<Address>(mActivity) {

                    @Override
                    public void onSuccess(Address address, Call call, Response response) {
                        if (mSwitchCompat.isChecked()) {
                            saveDefaultAddress(address);
                        }
                        EventBus.getDefault().post(new EventManager<>(LeEventCode.MSG_CODE_MODIFY_ADDRESS, address));
                        XToastUtils.showShortToast(getString(R.string.address_save_success));
                        setSaveBtnClickable(true);
                        delayBack();
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        XToastUtils.showShortToast(getString(R.string.address_save_fail));
                        setSaveBtnClickable(true);
                    }
                });
    }

    /**
     * 修改地址请求
     */
    private void upDateAddress() {
        int isDef = mSwitchCompat.isChecked() ? 1 : 0;
        long addressId = mAddress.getAddressId();
        String strAddress = mModifyViews.get(2).getModifyEditText() + mModifyViews.get(3).getModifyEditText();
        AddressApi.updateAddress(mActivity, userId, supplierId, addressId, isDef, mModifyViews.get(0).getModifyEditText(),
                mModifyViews.get(1).getModifyEditText(), province, city, area, strAddress, mModifyViews.get(3).getModifyEditText(),
                new DialogCallback<Address>(mActivity) {

                    @Override
                    public void onSuccess(Address address, Call call, Response response) {
                        if (mSwitchCompat.isChecked()) {
                            saveDefaultAddress(address);
                        }
                        if (isDefault && !mSwitchCompat.isChecked()) {
                            clearDefaultAddress();
                        }
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_MODIFY_ADDRESS, address));
                        XToastUtils.showShortToast(getString(R.string.address_modify_success));
                        setSaveBtnClickable(true);
                        delayBack();
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        XToastUtils.showShortToast(getString(R.string.address_modify_fail));
                        setSaveBtnClickable(true);
                    }
                });
    }


    /**
     * 删除收货地址请求
     */
    private void delAddress() {
        long addressId = mAddress.getAddressId();
        AddressApi.delAddress(mActivity, userId, supplierId, addressId, new DialogCallback<Address>(mActivity) {

            @Override
            public void onSuccess(Address address, Call call, Response response) {
                if (isDefault) {
                    clearDefaultAddress();
                }
                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_MODIFY_DEL_ADDRESS, mAddress));
                XToastUtils.showShortToast(getString(R.string.address_del_success));
                setSaveBtnClickable(true);
                delayBack();
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                XToastUtils.showShortToast(getString(R.string.address_del_fail));
                setSaveBtnClickable(true);
            }
        });
    }


    /**
     * 清除
     */
    private void clearDefaultAddress() {
        AsyncTaskUtils.exe(new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                Utils.clearDefaultAddress();
                return null;
            }
        });
    }

    /**
     * 保存默认地址
     */
    private void saveDefaultAddress(Address address) {
        Utils.putDefaultAddress(address);
    }

    /**
     * 设置保存键是否可点击
     *
     * @param clickable
     */
    private void setSaveBtnClickable(boolean clickable) {
        if (mRoundTextView != null)
            mRoundTextView.setClickable(clickable);
    }

    /**
     * 延迟返回
     */
    private void delayBack() {
        ThreadPool.postOnUiDelayed(() -> pop(), 300);
    }


    @OnClick({R.id.tv_add_address})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_add_address:
                if (CheckUtils.isEmpty(mModifyViews.get(0).getModifyEditText())) {
                    XToastUtils.showShortToast(getString(R.string.modify_name_warn));
                    return;
                }
                if (CheckUtils.isEmpty(mModifyViews.get(1).getModifyEditText())) {
                    XToastUtils.showShortToast(getString(R.string.modify_phone_warn));
                    return;
                }
                if (!CheckUtils.isMobilePhone(mModifyViews.get(1).getModifyEditText())) {
                    XToastUtils.showShortToast(getString(R.string.wrong_phone_number));
                    return;
                }
                if (CheckUtils.isEmpty(province)) {
                    XToastUtils.showShortToast(getString(R.string.modify_province_warn));
                    return;
                }
                if (CheckUtils.isEmpty(mModifyViews.get(3).getModifyEditText())) {
                    XToastUtils.showShortToast(getString(R.string.modify_detail_warn));
                    return;
                }
                if (change) {
                    upDateAddress();
                } else {
                    addAddress();
                }
                setSaveBtnClickable(false);
                break;
        }
    }


    /**
     * 省市区点击事件
     *
     * @param tag
     */
    @Override
    public void onItemClick(int tag) {
        switch (tag) {
            case TAG_SELECT_CITY:
                if (mCityPickerView != null) {
                    hideSoftInput();
                    mCityPickerView.show();
                } else {
                    XToastUtils.showShortToast(mActivity.getResources().getString(R.string.loading_province_data));
                }
                break;
        }
    }


    @Override
    public void btnRightTextClick() {
        super.btnRightTextClick();
        if (change) {
            delAddress();
            setSaveBtnClickable(false);
        }
    }

    /**
     * 获取地址 并解析
     */
    private void getAddress() {
        mParseTask = new ParseTask();
        mParseTask.execute();
    }

    /**
     * 解析任务
     */
    private class ParseTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            AddressUtils.getAddressJsonString();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            list1 = Utils.getProvinceList();
            list2 = Utils.getCityList();
            list3 = Utils.getDistrictList();
            getNameById();
        }
    }

    /**
     * 如果是修改，根据id 获取那么
     */
    private void getNameById() {
        int index1 = -1, index2 = -1, index3 = -1;
        //如果是修改地址，根据返回的编码查出对应地址
        if (change) {
            if (mModifyViews == null) {
                return;
            }
            if (!CheckUtils.isEmpty(mAddress.getProvince())) {
                index1 = AddressUtils.getIndexByIdList1(mAddress.getProvince(), list1);
            }
            if (index1 != -1) {
                provinceStr = Utils.getProvinceList().get(index1).getName();
                if (!CheckUtils.isEmpty(mAddress.getCity())) {
                    index2 = AddressUtils.getIndexByIdList2(mAddress.getCity(), index1, list2);
                }
            } else {
                index1 = 0;
            }
            if (index2 != -1) {
                cityStr = Utils.getCityList().get(index1).get(index2).getName();
                if (!CheckUtils.isEmpty(mAddress.getArea())) {
                    index3 = AddressUtils.getIndexByIdList3(mAddress.getArea(), index1, index2, list3);
                }
                if (index3 != -1) {
                    areaStr = Utils.getDistrictList().get(index1).get(index2).get(index3).getName();
                } else {
                    index3 = 0;
                }
            } else {
                index2 = 0;
            }
            CLog.i("hcy", "index1 = " + index1 + "--index2 = " + index2 + "--index3 = " + index3);
            StringBuilder builder = new StringBuilder(provinceStr);
            builder.append(cityStr).append(areaStr);
            if (mModifyViews == null) {
                return;
            }
            mModifyViews.get(2).setModifyItemText(builder.toString());
            setSaveBtnClickable(true);
            initCityPicker(index1, index2, index3);
        } else {
            initCityPicker(0, 0, 0);
        }
    }

    @Override
    public void btnLeftImageClick() {
        isCityPickerViewShow();
    }

    @Override
    public boolean onBackPressedSupport() {
        isCityPickerViewShow();
        return true;
    }

    /**
     * 省市区选择框显示就dismiss，否则返回
     */
    private void isCityPickerViewShow() {
        if (mCityPickerView != null && mCityPickerView.isShowing()) {
            mCityPickerView.dismiss();
        } else {
            mActivity.onBackPressedSupport();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消Task
        if (mAsyncTask != null) {
            mAsyncTask.cancel(true);
        }
        if (mParseTask != null) {
            mParseTask.cancel(true);
        }
    }
}
